package com.example.demo.controler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.bean.Dianzan;
import com.example.demo.bean.Picture;
import com.example.demo.bean.Pinglun;
import com.example.demo.bean.User;
import com.example.demo.service.DianzanService;
import com.example.demo.service.PictureService;
import com.example.demo.service.PinglunService;
import com.example.demo.service.UserService;
import com.example.demo.util.QiniuCloudUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liaoxh
 * @create 2021-06-09-19:53
 */
@Controller
public class UserControl {
    @Autowired
    UserService userService;
    @Autowired
    PictureService pictureService;
    @Autowired
    PinglunService pinglunService;
    @Autowired
    DianzanService dianzanService;

    @RequestMapping("/login")
    @ResponseBody
    public  User login(HttpServletRequest request){
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        User user = userService.getByName(name);
        if(user == null){}
        else {
            if(user.getPassword().equals(password))
                return user;
        }
        System.out.println(user);
        return  null;
    }
    @RequestMapping("/info")
    @ResponseBody
    public  User info(@RequestBody String s,HttpServletRequest request){
        ObjectMapper mapper = new ObjectMapper();
        Map map = null;
        try {
            map = mapper.readValue(s, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String url=null;
        Object data = map.get("data");
        if (data != null){
            url = getUrl(data.toString());
        }
        Integer userId = Integer.valueOf((String)map.get("userId"));
        String name = (String) map.get("name");
        String password = (String) map.get("password");
        User olduser = userService.getByName(name);
        if(olduser!=null) return null;
        User user = userService.getById(userId);
        user.setPassword(password);
        user.setName(name);
        if (url!=null)user.setHeadUrl(url);
        userService.updateById(user);
        System.out.println(user);
        return user;
    }
    public String getUrl(String data){
        QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
        String url=null;
        String imageName = null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        try {
            b = decoder.decodeBuffer(data);
            imageName = UUID.randomUUID().toString().replaceAll("-", "");
            url = qiniuUtil.put64image(b, imageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
    @RequestMapping("/register")
    @ResponseBody
    public  String register(@RequestBody String s,HttpServletRequest request){
        ObjectMapper mapper = new ObjectMapper();
        Map map = null;
        try {
            map = mapper.readValue(s, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String name = (String) map.get("name");
        String password = (String) map.get("password");
        User user = userService.getByName(name);
        if(user!=null){
            return "fail";
        }
            else{

            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            String url=null;
            String imageName = null;
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(map.get("data").toString());
                imageName = UUID.randomUUID().toString().replaceAll("-", "");
                url = qiniuUtil.put64image(b, imageName);
            } catch (Exception e) {
                e.printStackTrace();
            }
                user = new User();
                user.setName(name);
                user.setPassword(password);
                user.setHeadUrl(url);
                userService.save(user);
                return "sucess";
            }

    }

    @RequestMapping("/hh")
    @ResponseBody
    public String hh(@RequestBody String s, HttpServletRequest request) throws JsonProcessingException, Base64DecodingException {

        /*File file = (File)request.getAttribute("file");
        String filename = file.getName();
        System.out.println(filename);*/
       // Object data = request.getAttribute("data");

        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(s, Map.class);
        String title = (String) map.get("title");
        String miaoshu = (String) map.get("miaoshu");
        String userId =(String) map.get("userId");
        QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
        String url=null;
        String imageName = null;
        //byte[] bytes = map.get("data").toString().getBytes();
        //String decodedString =new String(Base64.decode(bytes));
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        try {
            b = decoder.decodeBuffer(map.get("data").toString());
            imageName = UUID.randomUUID().toString().replaceAll("-", "");
            url = qiniuUtil.put64image(b, imageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url);
        Picture picture = new Picture();
        picture.setImUrl(url);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        picture.setTime(f.format(new Date()));
        picture.setUserId(Integer.valueOf(userId));
        picture.setMiaoshu(miaoshu);
        picture.setTitle(title);
        picture.setZanNum(0);
        pictureService.save(picture);

        return "succes";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public  String hello(MultipartFile file){

        return  file.getName();
    }

    public static boolean generateImage(String imgStr, String filename) {

                 if (imgStr == null) {
                         return false;
                     }
            BASE64Decoder decoder = new BASE64Decoder();
               try {
                        // 解密
                       byte[] b = decoder.decodeBuffer(imgStr);
                         // 处理数据
                         for(int i = 0; i < b.length; ++i) {
                               if (b[i] < 0) {
                                        b[i] += 256;
                                   }
                    }
                       OutputStream out = new FileOutputStream("D:/tempZip/"+filename);
                        out.write(b);
                        out.flush();
                       out.close();
                       return true;
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                return false;

             }
    @ResponseBody
    @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
    public String uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {

        if (image.isEmpty()) {
            return "fail";
        }

        try {
            byte[] bytes = image.getBytes();
            String imageName = UUID.randomUUID().toString();

            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "succ";
        } catch (IOException e) {
            return "fail";
        }
    }

    @RequestMapping("/all")
    @ResponseBody
    public String all(HttpServletRequest request,HttpServletResponse response){
        Integer userId = Integer.valueOf(request.getParameter("userId"));
        String[]item =new String[]{"id","userId","time","zanNum"};
        int[]type = new int[]{0,1};
        java.util.Random r=new java.util.Random();
        int x = Math.abs(r.nextInt());
        int y = Math.abs(r.nextInt());
        QueryWrapper wrapper = new QueryWrapper();
        y=y%4;
        x=x%2;
        if(x==1){
            wrapper.orderByAsc(item[y]);
        }
        else wrapper.orderByDesc(item[x]);
        System.out.println("x="+x+";y="+y);
        System.out.println("wrapper is "+wrapper.toString());
        List<Picture> list = pictureService.list(wrapper);
        System.out.println(list);
        //for(Picture picture :list){
        for(int i = 0;i < list.size(); i ++){
            Picture picture =list.get(i);
            picture.setUser(userService.getById(picture.getUserId()));
            if (dianzanService.getByPUId(userId, picture.getId())!=null) {
                System.out.println("userid=" + userId + ",pictureid" + picture.getId());
                picture.setIsZan(true);
            }
            else  picture.setIsZan(false);
        }
        HashMap map =new HashMap();
        map.put("pictrueslist", list);
        ObjectMapper mapper = new ObjectMapper();
        String s = null;
        try {
            s = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
       // resp.
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(s.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
       // response.addHeader("pictrueslist", s);
        return s;
    }

    @ResponseBody
    @RequestMapping("/pinglun")
    public HashMap getPinglun(HttpServletRequest request){


        Integer pictureId = Integer.valueOf(request.getParameter("pictureId"));
        List<Pinglun> list = pinglunService.getByPictureId(pictureId);
        for(Pinglun p :list){
            p.setUser(userService.getById(p.getUserId()));
        }
        HashMap map = new HashMap();
        map.put("pinglunList", list);
        System.out.println("getPL");
        return map;

    }
    @ResponseBody
    @RequestMapping("/addPl")
    public HashMap addPl(HttpServletRequest request){
        Integer userId = Integer.valueOf(request.getParameter("userId"));
        Integer pictureId = Integer.valueOf(request.getParameter("pictureId"));
        String pinglun = request.getParameter("pinglun");
        Pinglun p = new Pinglun();
        p.setUser(userService.getById(userId));
        p.setPictureId(pictureId);
        p.setPinglun(pinglun);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        p.setUserId(p.getUser().getId());
        p.setTime(f.format(new Date()));
        pinglunService.save(p);
        HashMap map = new HashMap();
        System.out.println("addPL"+p);
        map.put("plEntry", p);
        return map;

    }
    @ResponseBody
    @RequestMapping("/addZan")
    public void addZan(HttpServletRequest request){
        Integer userId = Integer.valueOf(request.getParameter("userId"));
        Integer pictureId = Integer.valueOf(request.getParameter("pictureId"));
        Dianzan dianzan = dianzanService.getByPUId(userId, pictureId);
        if(dianzan == null){
            dianzan =new Dianzan();
            dianzan.setPictureId(pictureId);
            dianzan.setUserId(userId);
            dianzanService.save(dianzan);
            Picture picture = pictureService.getById(pictureId);
            picture.setZanNum(picture.getZanNum()+1);
            pictureService.updateById(picture);
        }
        else{
            dianzanService.removeById(dianzan.getId());
            Picture picture = pictureService.getById(pictureId);
            picture.setZanNum(picture.getZanNum()-1);
            pictureService.updateById(picture);
        }

    }

}
